// models/product.js
module.exports = (sequelize, DataTypes) => {
    const Product = sequelize.define('Product', {
        rjCode: {
            type: DataTypes.STRING,
            primaryKey: true,
            allowNull: false
        },
        folderAlias: DataTypes.STRING,
        filePath: DataTypes.STRING,
        title: DataTypes.STRING,
        translatedTitle: DataTypes.STRING,
        circleID: {
            type: DataTypes.INTEGER,  // 修改 circle 为 INTEGER 类型
            allowNull: true,          // 一个 Product 可能没有 Circle
        },
        seriesID: {
            type: DataTypes.INTEGER,  // 修改 Series 为 INTEGER 类型
            allowNull: true,          // 一个 Product 可能没有 Series
        },
        workType: DataTypes.STRING,
        ageCategory: DataTypes.STRING,
        releaseDate: DataTypes.DATE,
        price: DataTypes.INTEGER,
        sales: DataTypes.INTEGER,
        favorites: DataTypes.INTEGER,
        rating: DataTypes.FLOAT,
        ratingCount: DataTypes.INTEGER,
        lang: DataTypes.STRING,
        isSub: DataTypes.BOOLEAN,
        isVR: DataTypes.BOOLEAN,
        saleDetail: {
            type: DataTypes.TEXT,
            get() {
                const rawValue = this.getDataValue('saleDetail');
                return rawValue ? JSON.parse(rawValue) : [];
            },
            set(value) {
                this.setDataValue('saleDetail', JSON.stringify(value));
            }
        },
        ratingDetail: {
            type: DataTypes.TEXT,
            get() {
                const rawValue = this.getDataValue('ratingDetail');
                return rawValue ? JSON.parse(rawValue) : [];
            },
            set(value) {
                this.setDataValue('ratingDetail', JSON.stringify(value));
            }
        },
    }, {
        tableName: 'Product'  // 对应数据库的 Products 表
    });

    Product.associate = (models) => {
        Product.belongsTo(models.Circle, {
            foreignKey: 'circleID',
            as: 'circle'
        });
        Product.belongsTo(models.Series, {
            foreignKey: 'seriesID',
            as: 'series'
        });
        Product.belongsToMany(models.Tag, {
            through: models.ProductTags,
            foreignKey: 'rjCode',
            otherKey: 'tagID',
            as: 'tags'
        });
        Product.belongsToMany(models.VA, {
            through: models.ProductVA,
            foreignKey: 'rjCode',
            otherKey: 'vaID',
            as: 'vas'
        });
    };

    return Product;
};

